package com.example.chatapp.websocket;

import jakarta.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket 握手拦截器（将 HTTP session 中的 username / roomId 注入 WebSocket session attributes）
 */
public class HttpHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, org.springframework.http.server.ServerHttpResponse response,
                                   org.springframework.web.socket.WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest servletReq) {
            HttpSession httpSession = servletReq.getServletRequest().getSession(false);
            if (httpSession != null) {
                Object username = httpSession.getAttribute("username");
                Object roomId = httpSession.getAttribute("roomId");
                String user = username != null ? username.toString() : "guest";
                String room = roomId != null ? roomId.toString() : "default";
                attributes.put("username", user);
                attributes.put("roomId", room);
                System.out.println("[HttpHandshakeInterceptor] WebSocket handshake - username: " + user + ", roomId: " + room);
            } else {
                attributes.put("username", "guest");
                attributes.put("roomId", "default");
                System.out.println("[HttpHandshakeInterceptor] No HTTP session found, using defaults");
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, org.springframework.http.server.ServerHttpResponse response,
                               org.springframework.web.socket.WebSocketHandler wsHandler, Exception exception) { }
}
